package _7z

import (
	"github.com/bodgit/sevenzip"
	"io"
	"log/slog"
	"os"
	"path/filepath"
)

func extractFile(f *sevenzip.File, saveRoot string) error {
	var err error
	var rc io.ReadCloser
	var output *os.File
	rc, err = f.Open()
	if err != nil {
		return err
	}
	defer rc.Close()

	if err = os.MkdirAll(saveRoot+"/"+filepath.Dir(f.Name), os.ModePerm); err != nil {
		return err
	}

	output, err = os.OpenFile(saveRoot+"/"+f.Name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.FileInfo().Mode())
	if err != nil {
		return err
	}
	defer output.Close()
	_, err = io.Copy(output, rc)
	return err
}

func ExtractAll(reader *sevenzip.ReadCloser, saveRoot string) {
	if len(saveRoot) == 0 {
		saveRoot = "."
	}
	var err error
	for _, f := range reader.File {
		if f.FileInfo().IsDir() {
			err = os.MkdirAll(saveRoot+"/"+f.Name, f.Mode())
		} else {
			err = extractFile(f, saveRoot)
			if err != nil {
				slog.Error(err.Error())
			}
		}
	}
}

func ExtractSome(reader *sevenzip.ReadCloser, fileList []string, saveRoot string) {
	if len(saveRoot) == 0 {
		saveRoot = "."
	}
	var err error
	m := make(map[string]bool)
	for _, v := range fileList {
		m[v] = true
	}
	for _, f := range reader.File {
		if m[f.FileInfo().Name()] {
			err = extractFile(f, saveRoot)
			if err != nil {
				slog.Error(err.Error())
			}
		}
	}
}
